package com.teamin.service.Jobs;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teamin.entity.JobAndTrigger;
import com.teamin.mapper.JobAndTriggerMapper;
import com.teamin.service.BaseJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class JobAndTriggerImpl implements IJobAndTriggerService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());


	@Autowired
	private JobAndTriggerMapper jobAndTriggerMapper;

	@Autowired
	Scheduler sched;

	public PageInfo<JobAndTrigger> getJobAndTriggerDetails(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<JobAndTrigger> list = jobAndTriggerMapper.getJobAndTriggerDetails();
		PageInfo<JobAndTrigger> page = new PageInfo<JobAndTrigger>(list);
		return page;
	}

	@Override
	public void jobdelete(String key, String jobGroupName) throws Exception {
		// 通过SchedulerFactory获取一个调度器实例
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler sched = sf.getScheduler();
		sched.pauseTrigger(TriggerKey.triggerKey(key, jobGroupName));
		sched.unscheduleJob(TriggerKey.triggerKey(key, jobGroupName));
		sched.deleteJob(JobKey.jobKey(key, jobGroupName));
	}

	@Override
	public void addTaskJob(Long taskId ,Long remindTime){
		// 通过SchedulerFactory获取一个调度器实例
		if(remindTime < System.currentTimeMillis())
			return ;

		Map<String,Object> map = new HashMap<>() ;
		map.put("taskId",taskId) ;
		try {
			addJob(CLASS_TASK_REMIND,GROU_NAME_TASK,""+taskId,remindTime,map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteTaskJob(Long taskId){
		try {
			jobdelete(""+taskId,GROU_NAME_TASK);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addJob(String jobClassName, String jobGroupName,String key,Long remindTime,Map<String,Object> dataMap)throws Exception{
		//先删除之前的JOB
		jobdelete(key,jobGroupName);
		// 通过SchedulerFactory获取一个调度器实例
		//构建job信息
		JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(key, jobGroupName).build();
		if(dataMap != null) {
			dataMap.forEach((k,v)->{
				jobDetail.getJobDataMap().put(k, v);
			});
		}
		logger.info("-------------------------------------"+new Date(remindTime));
		//按新的cronExpression表达式构建一个新的trigger
		//CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
		//CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobGroupName)
		//		.withSchedule(scheduleBuilder).build();
		SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity(key,jobGroupName).
				startAt(new Date(remindTime)).build();
		try {
			sched.scheduleJob(jobDetail, simpleTrigger);
		} catch (SchedulerException e) {
			System.out.println("创建定时任务失败"+e);
			throw new Exception("创建定时任务失败");
		}
	}

	public BaseJob getClass(String classname) throws Exception{
		Class<?> class1 = Class.forName(classname);
		return (BaseJob)class1.newInstance();
	}

	@Override
	public void jobPause(String jobClassName, String jobGroupName) throws Exception{
		// 通过SchedulerFactory获取一个调度器实例
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler sched = sf.getScheduler();
		sched.pauseJob(JobKey.jobKey(jobClassName, jobGroupName));
	}

	@Override
	public void jobresume(String jobClassName, String jobGroupName) throws Exception{
		// 通过SchedulerFactory获取一个调度器实例
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler sched = sf.getScheduler();
		sched.resumeJob(JobKey.jobKey(jobClassName, jobGroupName));
	}

	@Override
	public void jobreschedule(String jobClassName, String jobGroupName, String cronExpression) throws Exception{
		try {
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			Scheduler scheduler = schedulerFactory.getScheduler();
			TriggerKey triggerKey = TriggerKey.triggerKey(jobClassName, jobGroupName);
			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

			// 按新的cronExpression表达式重新构建trigger
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

			// 按新的trigger重新设置job执行
			scheduler.rescheduleJob(triggerKey, trigger);
		} catch (SchedulerException e) {
			System.out.println("更新定时任务失败"+e);
			throw new Exception("更新定时任务失败");
		}
	}
}